package tut.mysql.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Db {
	private Connection connection = null;
	private Statement stmt = null;

	private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";

	private String dbServer = ""; // ip:port
	private String user = "";
	private String password = "";
	private String database = "";

	public Db(String dbServer, String user, String password, String database) {
		this.dbServer = dbServer;
		this.user = user;
		this.password = password;
		this.database = database;
	}

	private void createNewConnection() throws Exception {

		StringBuffer url = new StringBuffer();
			url
			.append("jdbc:mysql://")
			.append(this.dbServer)
			.append("/")
			.append(this.database)
			.append("?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull")
			;

			// ドライバクラスをロード
			Class.forName(DRIVER_CLASS);

		// データベースへ接続
		DriverManager.setLoginTimeout(10);
		this.connection = DriverManager.getConnection(url.toString(), this.user, this.password);
		this.stmt = this.connection.createStatement();
	}

	public  Connection getConnection() throws Exception {
		// 未接続なら接続する
		if(this.connection == null) {
			createNewConnection();
		}

		return this.connection;
	}

	public boolean executeUpdate(String SQL) throws Exception {
		this.getStatement().executeUpdate(SQL);
		return true;
	}

	public Statement getStatement () throws Exception{
		if(this.stmt == null) {
			createNewConnection();
		}

		return this.stmt;
	}

	public void closeConnection(){
		if(this.connection == null) return;

		try{
			this.connection.close();
		}catch(Exception e){

		}

		this.connection = null;
		this.stmt = null;
	}
}
